import 'dart:async';

import 'package:flutter/material.dart';

class UIHelper {
  UIHelper._();

  static Rect? findGlobalRect(GlobalKey key) {
    RenderObject? renderObject = key.currentContext?.findRenderObject();
    if (renderObject == null) {
      return Rect.zero;
    }

    if (renderObject is! RenderBox) {
      return null;
    }

    var globalOffset = renderObject.localToGlobal(Offset.zero);

    var bounds = renderObject.paintBounds;
    bounds = bounds.translate(globalOffset.dx, globalOffset.dy);
    return bounds;
  }

  static Future<Rect> measureWidgetRect({
    required BuildContext context,
    required Widget widget,
    required BoxConstraints boxConstraints,
  }) {
    Completer<Rect> completer = Completer();
    late OverlayEntry entry;
    entry = OverlayEntry(builder: (BuildContext ctx) {
      print(Theme.of(context).platform);
      return MeasureWidget(
        boxConstraints: boxConstraints,
        measureRect: (rect) {
          entry.remove();
          completer.complete(rect);
        },
        child: widget,
      );
    });

    Overlay.of(context).insert(entry);
    return completer.future;
  }
}

class MeasureWidget extends StatefulWidget {
  final Widget child;
  final ValueSetter<Rect?> measureRect;
  final BoxConstraints boxConstraints;

  const MeasureWidget({
    super.key,
    required this.child,
    required this.measureRect,
    required this.boxConstraints,
  });

  @override
  MeasureWidgetState createState() => MeasureWidgetState();
}

class MeasureWidgetState extends State<MeasureWidget> {
  GlobalKey key = GlobalKey();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback(afterFirstLayout);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Offstage(
      offstage: true,
      child: Center(
        child: Container(
          key: key,
          // constraints: widget.boxConstraints,
          child: widget.child,
        ),
      ),
    );
  }

  void afterFirstLayout(Duration context) {
    Rect? rect = UIHelper.findGlobalRect(key);
    widget.measureRect.call(rect);
  }
}
